'use strict';
const path = require('path')
const cp = require('child_process')
const Package = require('@imooc-cli-dev-dq/package')
const log = require('@imooc-cli-dev-dq/log')
const {exec: spawn} = require('@imooc-cli-dev-dq/utils')

const SETTINGS = {
    init: '@imooc-cli-dq-core/init',
    exec: '@imooc-cli/init'
}
const CACHE_DIR = './dependencies'

async function index() {
    // TODO
    let targetPath = process.env.CLI_TARGET_PATH
    const homePath = process.env.CLI_HOME_PATH
    let storeDir = ''
    let pkg = ''
    log.verbose('targetPath', targetPath)
    log.verbose('homePath', homePath)
    const cmbObj = arguments[arguments.length - 1]
    const cmbName = cmbObj.name()
    const packageName = SETTINGS[cmbName]
    const packageVersion = 'latest'
    
    if (!targetPath) {

        targetPath = path.resolve(homePath, CACHE_DIR) // 缓存路径
        storeDir = path.resolve(targetPath, 'node_modules')
        pkg = new Package({
            targetPath,
            storeDir,
            packageName,
            packageVersion
        })
        if (await pkg.exists()) {
            // 更新pkg
            await pkg.update()
        } else {
            // 安装pkg
          await pkg.install()
    
        }

    } else {
        pkg = new Package({
            targetPath,
            packageName,
            packageVersion
        }) 
    }
    const rootFile = pkg.getRootFilePath()
    if (rootFile) {
        try {
            // require(rootFile).call(null, Array.from(arguments))
            const args = Array.from(arguments)
            const cmd = args[args.length - 1]
            const o = Object.create(null)
    
            Object.keys(cmd).forEach(key => {
                if (cmd.hasOwnProperty(key) &&
                  !key.startsWith('_') &&
                  key !== 'parent') {
                  o[key] = cmd[key];
                }
              });
            args[args.length - 1] = o
        
            const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`;
            const child = spawn('node', ['-e', code], {
              cwd: process.cwd(),
              stdio: 'inherit',
            });
            child.on('error', e => {
                log.error(e.message)
                process.exit(1)
            })
            child.on('exit', e => {
                log.verbose('命令执行成功:' + e)
                process.exit(e)
            })
            // child.stdout.on('data', (chunk => {
                
            // }))
            // child.stderr.on('data', (chunk => {

            // }))
        } catch (e) {
            log.error(e.message)
        }
        // require(rootFile)(arguments)
    
    }


}
module.exports = index;